<template>
  <div>
    <Card dis-hover>
      <!-- 查询条件 -->
      <Row>
        <Form :model="params" inline :label-width="100">
          <Col :span="8">
            <FormItem label="状态：">
              <Select v-model="params.state" clearable>
                <Option v-for="item in mqttUserStateEnum" :key="item.code" :value="item.code">{{item.desc}}</Option>
              </Select>
            </FormItem>
          </Col>
        </Form>
        <div style="position:relative; float:right;bottom:0px;">
          <Button type="primary" @click="handleQuery">查询</Button>
        </div>
      </Row>
      <!-- 增加、批量处理命令 -->
      <Row>
        <Col :span="12">
          <Button type="primary" @click="showRegister">登记</Button>
          <Button type="warning" @click="syncRedis">同步redis</Button>
        </Col>
      </Row>
    </Card>
    <!-- 列表 -->
    <div class="view-table">
      <Table :data="tableData"
             :columns="tableColumns"
             size="small"
             highlight-row
             :loading="isLoading"
             @on-selection-change="select"
             ref="table">
        <template slot-scope="{ row, index }" slot="action">
          <Button type="primary" ghost size="small" style="margin-right: 10px" @click="showTopicPermit(row)">主题授权
          </Button>
          <Dropdown :transfer="true" placement="bottom-start" @on-click="action">
            <Button type="text" size="small">
              更多
              <Icon type="ios-arrow-down"></Icon>
            </Button>
            <DropdownMenu slot="list">
              <DropdownItem :name="'closeUser:' + row._index">关闭</DropdownItem>
              <DropdownItem :name="'openUser:' + row._index">激活</DropdownItem>
            </DropdownMenu>
          </Dropdown>
        </template>
      </Table>
    </div>
    <!-- 分页 -->
    <div class="view-page">
      <Page :total="page.total"
            :current="page.currentPage"
            :page-size="page.pageSize"
            :page-size-opts="[10,20,50,100]"
            size="small"
            show-total
            show-elevator
            show-sizer
            @on-change="pageChange"
            @on-page-size-change="pageSizeChange"/>
    </div>
    <Register :visible.sync="registerFormVisible" @on-ok="handleQuery"></Register>
    <topic-permit :visible.sync="topicPermitFormVisible" :init-form-data="clickRow" @on-ok="handleQuery"></topic-permit>
  </div>
</template>

<script>
  import {timeToString} from "@/util/dateUtil"
  import {getMqttUserPage, closeUser, openUser,syncKauthRedis} from '@/api/mqtt/user'
  import {getMqttUserStateDesc, getMqttUserStateEnum} from "@/enum/MqttEnum"
  import Register from "./register"
  import TopicPermit from "./topicPermit"

  export default {
    name: "index",
    components: {Register, TopicPermit},
    data() {
      return {
        mqttUserStateEnum: getMqttUserStateEnum(),
        params: {
          state: null
        },
        moreCondition: false,
        tableData: [],
        tableColumns: [
          {
            type: 'selection',
            width: 60
          },
          {
            title: 'id',
            key: 'id',
            width: 60
          },
          {
            title: '用户名',
            key: 'userName',
            align: 'center'
          },
          {
            title: '状态',
            key: 'stateStr',
            align: 'center',
            width: 120
          },
          {
            title: '创建时间',
            key: 'createdTimeStr',
            align: 'center',
            width: 180
          },
          {
            title: '操作',
            slot: 'action',
            width: 200,
            align: 'center',
            fixed: 'right'
          }
        ],
        selection: [],
        clickRow: {},
        isLoading: false,
        page: {
          total: 0,
          currentPage: 1,
          pageSize: 10
        },
        registerFormVisible: false,
        topicPermitFormVisible: false,
      }
    },
    created() {
      this.query()
    },
    methods: {
      handleQuery() {
        this.page = {
          total: 0,
          currentPage: 1,
          pageSize: 10
        }
        this.query()
      },
      query() {
        const self = this
        self.isLoading = true
        let params = {
          currentPage: self.page.currentPage,
          pageSize: self.page.pageSize,
          state: self.params.state
        }
        getMqttUserPage(params)
          .then((response) => {
            let result = response.data
            self.tableData = result.data
            for (let i = 0; i < self.tableData.length; i++) {
              const element = self.tableData[i];
              if (element.createdTime != null) {
                element.createdTimeStr = timeToString(element.createdTime)
              }
              if (element.state != null) {
                element.stateStr = getMqttUserStateDesc(element.state)
              }
            }
            self.page.total = result.total

            self.isLoading = false
          })
          .catch((err) => {
            self.isLoading = false
            self.$Message.error({
              content: err,
              duration: 10,
              closable: true
            })
          })
      },
      select(selection) {
        this.selection = selection
      },
      pageChange(currentPage) {
        this.page.currentPage = currentPage
        this.query()
      },
      pageSizeChange(pageSize) {
        this.page.pageSize = pageSize
        this.query()
      },
      showRegister() {
        this.registerFormVisible = true
      },
      showTopicPermit(row) {
        this.clickRow = row
        this.topicPermitFormVisible = true
      },
      closeUser(index) {
        let self = this
        let row = self.tableData[index]
        self.$Modal.confirm({
          "title": "提醒",
          "content": "是否关闭用户[" + row.userName + "]?",
          "onOk": () => {
            let params = {
              id: row.id
            }
            closeUser(params)
              .then(response => {
                self.$Message.success({
                  content: '关闭用户成功'
                })
                this.handleQuery()
              })
              .catch((err) => {
                self.$Message.error({
                  content: err,
                  duration: 10,
                  closable: true
                })
              })
          },
          "onCancel": () => {
          }
        })
      },
      openUser(index) {
        let self = this
        let row = self.tableData[index]
        self.$Modal.confirm({
          "title": "提醒",
          "content": "是否激活用户[" + row.userName + "]?",
          "onOk": () => {
            let params = {
              id: row.id
            }
            openUser(params)
              .then(response => {
                self.$Message.success({
                  content: '激活用户成功'
                })
                this.handleQuery()
              })
              .catch((err) => {
                self.$Message.error({
                  content: err,
                  duration: 10,
                  closable: true
                })
              })
          },
          "onCancel": () => {
          }
        })
      },
      action(cmd) {
        if (cmd.indexOf('closeUser') > -1) {
          let index = cmd.split(':')[1];
          this.closeUser(index);
        } else if (cmd.indexOf('openUser') > -1) {
          let index = cmd.split(':')[1];
          this.openUser(index);
        }
      },
      syncRedis() {
        let self = this
        self.$Modal.confirm({
          "title": "提醒",
          "content": "是否同步数据库的用户、主题权限数据到redis?",
          "onOk": () => {
            syncKauthRedis()
              .then(response => {
                self.$Message.success({
                  content: '开始同步redis'
                })
              })
              .catch((err) => {
                self.$Message.error({
                  content: err,
                  duration: 10,
                  closable: true
                })
              })
          },
          "onCancel": () => {
          }
        })
      }
    }
  }
</script>

<style scoped>

</style>
